import "//unpkg.com/mathlive";
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Button, Modal, Input } from 'antd';
import { MathfieldElement } from "mathlive";

interface Props {
  value: string,
  isOpen: boolean,
  handleOk: (str: string) => void,
  handleCancel: () => void
  handleChange?: (str: string) => void
}

export default function Index(props: Props) {
  const { value, isOpen,
    handleOk, handleCancel,
    handleChange = () => { }
  } = props
  const [formulaVal, setFormulaVal] = useState("");

  const mf = useRef<MathfieldElement>(new MathfieldElement())

  const onChange = useCallback((evt: any) => {
    setFormulaVal(evt.target.value)
    handleChange(evt.target.value)
  }, [handleChange])

  const onOk = () => {
    handleOk(formulaVal)
    setFormulaVal('')
  }

  const onCancel = () => {
    setFormulaVal('')
    handleCancel()
  }

  useEffect(() => {
    if (isOpen && mf.current) {
      const onFocus = () => {
        window.mathVirtualKeyboard.visible = true;
      }
      document.querySelector('math-field')?.addEventListener('focus', onFocus);
      return () => {
        document.querySelector('math-field')?.removeEventListener('focus', onFocus)
      }
    }
  }, [isOpen])

  useEffect(() => {
    if (isOpen) {
      setFormulaVal(value)
    }
  }, [value])

  return <>
    <Modal
      title="公式输入"
      open={isOpen}
      onOk={onOk}
      onCancel={onCancel}
      zIndex={100}
    >
      <math-field
        ref={mf}
        style={{ width: '100%' }}
        onInput={onChange}
      > {formulaVal}
      </math-field>
    </Modal>
  </>
}